package edu.ccut.saturn.basecomponent.databasecomponent;

import java.sql.Connection;

import edu.ccut.saturn.basecomponent.database.IInsertSQLBuilder;
import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.ISaturnSQLBuilder;
import edu.ccut.saturn.basecomponent.database.SaturnSQLBuilderFactory;
import edu.ccut.saturn.basecomponent.database.SaturnSQLHandler;
import edu.ccut.saturn.basecomponent.database.util.SaturnDataUtil;
import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;

public class Insert extends DefaultComponent {
	
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		//插入数据组件
		debug(Messages.getString("Insert.1n6"), parameterContext); //$NON-NLS-1$
		SaturnData saturnData = (SaturnData)parameterContext.getParameterValue(0);
		//从数据项中读出数据库类型
		Connection conn = parameterContext.getConnection();
		String dbType = SaturnDataUtil.getStandardDBType(saturnData);
        ISaturnSQLBuilder builder = SaturnSQLBuilderFactory.getSaturnSQLBuilder(dbType);
		if (builder != null) {
			IInsertSQLBuilder insertSQLBuilder = builder.getInsertSQLBuilder(getBuilderType(saturnData));
			ISaturnSQL saturnSQL = insertSQLBuilder.build(saturnData, conn);
			int result = SaturnSQLHandler.executeUpdate(saturnSQL, conn);
			parameterContext.setParameter(1, result);
			parameterContext.setParameter(0, saturnData);
		}
	}
	private String getBuilderType(SaturnData saturnData){
		
		if(SaturnDataUtil.hasLOB(saturnData)){
			return ISaturnSQL.INSERT_LOB_OPERATION;
		}else{
			return ISaturnSQL.INSERT_OPERATION;
		}
	}
}
